package com.github.postsanf.yinian.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.YNAddress;
import com.github.postsanf.yinian.bean.YNShop;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNAddressResponse;
import com.github.postsanf.yinian.entity.YNShopResponse;
import com.github.postsanf.yinian.utils.BigDecimalUtil;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import cn.beecloud.BCPay;
import cn.beecloud.async.BCCallback;
import cn.beecloud.async.BCResult;
import cn.beecloud.entity.BCPayResult;

public class OrderActivity extends BaseActivity implements View.OnClickListener {
    private TextView order_name;
    private TextView order_telphone;
    private TextView order_address;
    private SimpleDraweeView order_shop_pic;
    private TextView order_shop_name;
    private TextView order_shop_price;
    private TextView order_num_cutdown;
    private TextView order_num_show;
    private TextView order_num_add;
    private RelativeLayout order_coupon_layout;
    private TextView order_coupon;
    private TextView order_num_total;
    private TextView order_add_shopcar;
    private TextView order_num_cashcomplete;
    private LinearLayout order_head;
    private RelativeLayout order_address_info;
    private ImageView order_pay_iv;
    private String itemid;
    private String micurl;
    public String addressid;
    private String couponPrice;
    private String postage = "5";
    private int shopNum = 1;
    private String shopPrice;
    private String totalPrice;
    private boolean isPaySelect = true;
    private String toastMsg;
    private String ebOrderID;
    private RelativeLayout order_pay_post;
    private TextView post_switch_content;
    private ToggleButton post_switch;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    showToast(toastMsg);
                    break;
                case 8:
                    String one = BigDecimalUtil.mul(String.valueOf(shopNum), shopPrice);
                    totalPrice = BigDecimalUtil.sub(one, couponPrice);
                    if (order_pay_post.getVisibility() == View.VISIBLE && post_switch.isChecked()) {
                        totalPrice = BigDecimalUtil.add(totalPrice, postage);
                        order_num_total.setText("合计：" + totalPrice + "元(含" + postage + "元运费)");
                    } else {
                        order_num_total.setText("合计：" + totalPrice + "元");
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);
        registerBoradcastReceiver();
        initView();
        getOrderShopDetail();
        showShopReceiverAddress();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mListReceiver);
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionUpdateShopReceiver);
        myIntentFilter.addAction(ACTIONs.actionUpdateShopAddress);
        registerReceiver(mListReceiver, myIntentFilter);
    }

    BroadcastReceiver mListReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionUpdateShopReceiver:
                    if (intent != null) {
                        YNAddress ynAddress = (YNAddress) intent.getSerializableExtra("YNAddress");
                        if (ynAddress != null) {
                            order_address_info.setVisibility(View.VISIBLE);
                            addressid = String.valueOf(ynAddress.getAddressID());
                            order_name.setText(ynAddress.getAddressReceiver());
                            order_address.setText(ynAddress.getAddressDetail());
                            order_telphone.setText(ynAddress.getAddressPhoneNumber());
                            ChangeDefaultAddress(String.valueOf(ynAddress.getAddressID()));
                        } else {
                            order_address_info.setVisibility(View.GONE);
                            order_address.setText("请先添加收货地址");
                        }
                    }
                    break;
                case ACTIONs.actionUpdateShopAddress:
                    if (intent != null) {
                        String intentAddressid = String.valueOf(intent.getIntExtra("addressid", 0));
                        if (intentAddressid.equals(addressid)) {
                            order_address_info.setVisibility(View.GONE);
                            order_address.setText("请先添加收货地址");
                        }
                    }
                    break;
            }
        }
    };


    private void ChangeDefaultAddress(String addressID) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put("userid", String.valueOf(application.getCurID()));
        mParam.put("addressID", addressID);
        StringRequest req = new StringRequest(getString(R.string.SHOP_URL) + getString(R.string.ynChangeDefaultAddress))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    private void initView() {
        itemid = getIntent().getStringExtra("itemid");
        micurl = getIntent().getStringExtra("micurl");
        couponPrice = getIntent().getStringExtra("couponPrice");
        postage = getIntent().getStringExtra("postage");
        findViewById(R.id.order_back).setOnClickListener(this);
        order_name = (TextView) findViewById(R.id.order_name);
        order_telphone = (TextView) findViewById(R.id.order_telphone);
        order_address = (TextView) findViewById(R.id.order_address);
        order_shop_pic = (SimpleDraweeView) findViewById(R.id.order_shop_pic);
        order_shop_name = (TextView) findViewById(R.id.order_shop_name);
        order_shop_price = (TextView) findViewById(R.id.order_shop_price);
        order_num_cutdown = (TextView) findViewById(R.id.order_num_cutdown);
        order_num_cutdown.setOnClickListener(this);
        order_num_show = (TextView) findViewById(R.id.order_num_show);
        order_num_add = (TextView) findViewById(R.id.order_num_add);
        order_num_add.setOnClickListener(this);
        order_coupon_layout = (RelativeLayout) findViewById(R.id.order_coupon_layout);
        order_coupon = (TextView) findViewById(R.id.order_coupon);
        if (!StringUtils.isEmpty(couponPrice) && Double.parseDouble(couponPrice) > 0) {
            order_coupon.setText("¥" + couponPrice + "专属优惠券");
            order_coupon_layout.setVisibility(View.VISIBLE);
        } else {
            couponPrice = "0";
            order_coupon_layout.setVisibility(View.GONE);
        }
        order_num_total = (TextView) findViewById(R.id.order_num_total);
        order_add_shopcar = (TextView) findViewById(R.id.order_add_shopcar);
        order_num_cashcomplete = (TextView) findViewById(R.id.order_num_cashcomplete);
        order_add_shopcar.setOnClickListener(this);
        order_num_cashcomplete.setOnClickListener(this);
        order_head = (LinearLayout) findViewById(R.id.order_head);
        order_address_info = (RelativeLayout) findViewById(R.id.order_address_info);
        order_head.setOnClickListener(this);
        order_pay_iv = (ImageView) findViewById(R.id.order_pay_iv);
        findViewById(R.id.order_pay_layout).setOnClickListener(this);
        order_pay_post = (RelativeLayout) findViewById(R.id.order_pay_post);
        if (MainActivity.goodsid == 1) {
            order_pay_post.setVisibility(View.VISIBLE);
        } else {
            order_pay_post.setVisibility(View.GONE);
        }
        post_switch_content = (TextView) findViewById(R.id.post_switch_content);
        post_switch = (ToggleButton) findViewById(R.id.post_switch);
        post_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                post_switch.setChecked(isChecked);
                if (post_switch.isChecked()) {
                    post_switch_content.setText("邮寄方式： 快递(" + postage + "元)");
                    totalPrice = BigDecimalUtil.add(totalPrice, postage);
                    order_num_total.setText("合计：" + totalPrice + "元(含" + postage + "元运费)");
                } else {
                    post_switch_content.setText("邮寄方式： 平邮");
                    totalPrice = BigDecimalUtil.sub(totalPrice, postage);
                    order_num_total.setText("合计：" + totalPrice + "元");
                }
            }
        });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.order_back:
                finish();
                break;
            case R.id.order_head:
                startActivity(new Intent(OrderActivity.this, ShopAddressListActivity.class));
                break;
            case R.id.order_num_cutdown:
                if (shopNum > 1) {
                    shopNum--;
                    order_num_show.setText(String.valueOf(shopNum));
                    String one = BigDecimalUtil.mul(String.valueOf(shopNum), shopPrice);
                    totalPrice = BigDecimalUtil.sub(one, couponPrice);
                    if (post_switch.isChecked()) {
                        totalPrice = BigDecimalUtil.add(totalPrice, postage);
                        order_num_total.setText("合计：" + totalPrice + "元(含" + postage + "元运费)");
                    } else {
                        order_num_total.setText("合计：" + totalPrice + "元");
                    }
                }
                break;
            case R.id.order_num_add:
                shopNum++;
                order_num_show.setText(String.valueOf(shopNum));
                String one = BigDecimalUtil.mul(String.valueOf(shopNum), shopPrice);
                totalPrice = BigDecimalUtil.sub(one, couponPrice);
                if (post_switch.isChecked()) {
                    totalPrice = BigDecimalUtil.add(totalPrice, postage);
                    order_num_total.setText("合计：" + totalPrice + "元(含" + postage + "元运费)");
                } else {
                    order_num_total.setText("合计：" + totalPrice + "元");
                }
                break;
            case R.id.order_pay_layout:
                if (isPaySelect) {
                    isPaySelect = false;
                    order_pay_iv.setImageResource(R.drawable.order_pay_unselected);
                    order_num_cashcomplete.setBackgroundResource(R.drawable.btn_cash_complete_seclect);
                } else {
                    isPaySelect = true;
                    order_pay_iv.setImageResource(R.drawable.order_pay_selected);
                    order_num_cashcomplete.setBackgroundResource(R.drawable.btn_cash_complete);
                }
                break;
            case R.id.order_add_shopcar:
                doShopCar();
                break;
            case R.id.order_num_cashcomplete:
                if (!isPaySelect) {
                    showToast("请勾选支付方式");
                    return;
                }
                if (StringUtils.isEmpty(addressid)) {
                    showToast("请编辑地址");
                    return;
                }
                doCashComplete();
                break;

        }
    }

    private void doCashComplete() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put("userid", String.valueOf(application.getCurID()));
        mParam.put("addressID", addressid);
        mParam.put("itemID", itemid);
        mParam.put("num", String.valueOf(shopNum));
        if (!StringUtils.isEmpty(micurl)) {
            mParam.put("orderAudio", micurl);
        }
        if (post_switch.isChecked()) {
            mParam.put("isMail", "yes");
        } else {
            mParam.put("isMail", "no");
        }
        StringRequest req = new StringRequest(getString(R.string.SHOP_URL) + getString(R.string.ynPlaceOrder))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        Log.i("xjs", "zsss==>" + s.toString());
                        try {
                            JSONObject resultOrder = new JSONObject(s.toString());
                            if (ReqUtils.isSuccess(resultOrder.optString("code"))) {
                                ebOrderID = resultOrder.optJSONArray("data").optJSONObject(0).optString("ebOrderID");
//                                String ebOrderTotalPrice = resultOrder.optJSONArray("data").optJSONObject(0).optString("ebOrderTotalPrice");
                                String ebOrderNumber = resultOrder.optJSONArray("data").optJSONObject(0).optString("ebOrderNumber");
                                HashMap<String, String> mapOptional = new HashMap<>();
                                mapOptional.put("userid", String.valueOf(application.getCurID()));
                                mapOptional.put("ebOrderID", ebOrderID);
                                mapOptional.put("ebOrderNumber", ebOrderNumber);
                                Log.i("xjs", "totalPrice==>" + totalPrice);
                                int zongPrice = BigDecimalUtil.multotal(totalPrice, "100");
                                Log.i("xjs", "zongPrice==>" + zongPrice);
                                if (zongPrice <= 0) {
                                    showToast("价格有误，处理中！");
                                    return;
                                }
                                BCPay.getInstance(OrderActivity.this).reqAliPaymentAsync("武汉市追忆那年网络科技有限公司", zongPrice,
                                        ebOrderNumber, mapOptional, callback);
                            } else {
                                showToast("异常");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void doShopCar() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put("userid", String.valueOf(application.getCurID()));
        mParam.put("itemID", itemid);
        mParam.put("num", String.valueOf(shopNum));
        mParam.put("type", "add");
        StringRequest req = new StringRequest(getString(R.string.SHOP_URL) + getString(R.string.ynManageCart))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        Log.i("xjs", "cat==>" + s.toString());
                        try {
                            JSONObject resultOrder = new JSONObject(s.toString());
                            if (ReqUtils.isSuccess(resultOrder.optString("code"))) {
                                startActivity(new Intent(OrderActivity.this, ShopCarListActivity.class));
                                finish();
                            } else {
                                showToast("异常");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    BCCallback callback = new BCCallback() {
        @Override
        public void done(BCResult bcResult) {
            final BCPayResult bcPayResult = (BCPayResult) bcResult;
            String result = bcPayResult.getResult();
            Log.d("yuhao", "result=" + "支付失败, 原因: " + bcPayResult.getErrCode() +
                    " # " + bcPayResult.getErrMsg() +
                    " # " + bcPayResult.getDetailInfo());
            if (result.equals(BCPayResult.RESULT_SUCCESS)) {
                toastMsg = "用户支付成功";
                startActivity(new Intent(OrderActivity.this, OrderListActivity.class).putExtra("ebOrderID", ebOrderID));
                finish();
            } else if (result.equals(BCPayResult.RESULT_CANCEL)) {
                toastMsg = "用户取消支付";
            } else if (result.equals(BCPayResult.RESULT_FAIL)) {
                toastMsg = "支付失败, 原因: " + bcPayResult.getErrCode() +
                        " # " + bcPayResult.getErrMsg() +
                        " # " + bcPayResult.getDetailInfo();
            }
            handler.sendEmptyMessage(1);
            if (bcPayResult.getId() != null) {
                //你可以把这个id存到你的订单中，下次直接通过这个id查询订单
                Log.w(TAG, "bill id retrieved : " + bcPayResult.getId());
                //根据ID查询，此处只是演示如何通过id查询订单，并非支付必要部分
                // getBillInfoByID(bcPayResult.getId());
            }
        }
    };

    private void getOrderShopDetail() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put("itemID", itemid);
        StringRequest req = new StringRequest(getString(R.string.SHOP_URL) + getString(R.string.ynGetSingleItemInfo))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNShopResponse resShop = gson.fromJson(s, YNShopResponse.class);
                        if (ReqUtils.isSuccess(resShop.getCode())) {
                            Log.i("xjs", "ordrerdetail==>" + s.toString());
                            YNShop ynShop = resShop.getData().get(0);
                            order_shop_name.setText(ynShop.getEbGoodsName());
                            shopPrice = ynShop.getEbGoodsPrice();
                            order_shop_price.setText("¥" + shopPrice + "/" + ynShop.getEbGoodsUnit());
                            ImageOptHelper.showFrescoTodayshow(Uri.parse(ynShop.getEbGoodsPic()), order_shop_pic, OrderActivity.this);
                            handler.sendEmptyMessage(8);
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void showShopReceiverAddress() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put("userid", String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(getString(R.string.SHOP_URL) + getString(R.string.ynShowAllAddress))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNAddressResponse resAddress = gson.fromJson(s, YNAddressResponse.class);
                        if (ReqUtils.isSuccess(resAddress.getCode())) {
                            List<YNAddress> YNAddresslist = resAddress.getData();
                            if (YNAddresslist != null && YNAddresslist.size() > 0) {
                                order_address_info.setVisibility(View.VISIBLE);
                                for (int i = 0; i < YNAddresslist.size(); i++) {
                                    YNAddress ynAddress = YNAddresslist.get(i);
                                    if (ynAddress.getIsDefault() == 1) {
                                        addressid = String.valueOf(ynAddress.getAddressID());
                                        order_name.setText(ynAddress.getAddressReceiver());
                                        order_address.setText(ynAddress.getAddressDetail());
                                        order_telphone.setText(ynAddress.getAddressPhoneNumber());
                                        break;
                                    }
                                }
                            } else {
                                order_address_info.setVisibility(View.GONE);
                                order_address.setText("请先添加收货地址");
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);

    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }

}
